﻿Imports FinanceiroDAL
Imports System.Text.RegularExpressions
Public Class ContasBLL
    Dim objDal As New ContasDAL
#Region "Propriedades"
    Property codigo As Integer
    Property descricao As String
    Property banco As Integer
    Property dtabertura As Date
    Property dtfechamento As Nullable(Of Date)
    Property agencia As Integer
    Property contacorrente As Integer
    Property gerente As String
    Property email As String
    Property saldoinicial As Decimal
    Property status As Integer
    Property tipoConta As String
#End Region
#Region "Construtores"
    Sub New()
    End Sub
    Sub New(ByVal codigo As Integer)
        carrega(codigo)
    End Sub
#End Region
#Region "limpar"
    Sub limpar()
        Me.codigo = Nothing
        Me.descricao = Nothing
        Me.banco = Nothing
        Me.dtabertura = Nothing
        Me.dtfechamento = Nothing
        Me.agencia = Nothing
        Me.contacorrente = Nothing
        Me.gerente = Nothing
        Me.email = Nothing
        Me.saldoinicial = Nothing
        Me.status = Nothing
        Me.tipoConta = Nothing
    End Sub
#End Region
#Region "Métodos"
    Function inserir() As Integer
        Dim datAbertura As DateTime = DateTime.Parse(Me.dtabertura)
        ' Dim datFecha As DateTime = DateTime.Parse(Me.dtfechamento)
        Dim ret As Boolean
        Dim tab As New DataTable
        Try
            objDal = New ContasDAL
            If (datAbertura <= Date.Now.ToShortDateString) Then
                If (Me.descricao <> "" And Me.tipoConta <> "Bancária") Then
                    If objDal.validaContasNB(Me.descricao, Me.banco) Then
                        If (tab.Rows.Count = 0) Then
                            ret = objDal.inserirConta(descricao, banco, dtabertura, dtfechamento, agencia, contacorrente, gerente, email, saldoinicial, status, tipoConta)
                        End If
                    Else : MsgBox("Verifique Duplicidade")
                    End If

                ElseIf (objDal.validaContas(Me.descricao, Me.banco, Me.agencia, Me.contacorrente)) Then
                    If (tab.Rows.Count = 0) Then
                        ret = objDal.inserirConta(descricao, banco, dtabertura, dtfechamento, agencia, contacorrente, gerente, email, saldoinicial, status, tipoConta)
                        '  ret = False
                    End If
                Else : Throw New Exception("Inserção não realizada, verifique duplicidade!")
                End If
            Else
                MsgBox("Data de fechamento Inválido!")
            End If
        Catch ex As Exception
            Throw New Exception("Inserção não realizada!")
        Finally
            objDal = Nothing
        End Try
        Return ret
    End Function

    Function Alterar() As Boolean
        Dim ret As Boolean
        Try
            objDal = New ContasDAL
            If (Me.valida) Then
                If (objDal.validaAlteracao(Me.descricao, Me.codigo) = True) Then
                    ret = objDal.alterar(Me.codigo, Me.descricao, Me.banco, Me.dtabertura, Me.dtfechamento, Me.agencia, Me.contacorrente, Me.gerente, Me.email, Me.saldoinicial, Me.status, Me.tipoConta)
                Else : Throw New Exception("Conta já cadastrada.")
                End If
            Else
                Throw New Exception("Preencha todos os campos.")
            End If
        Catch ex As Exception
            Throw ex
        Finally
            objDal = Nothing
        End Try
        Return ret
    End Function
    Function Excluir(ByVal Codigo As Integer) As Boolean
        Dim ret As Boolean
        Dim tab As New DataTable
        Try
            objDal = New ContasDAL
            tab = objfuncoes.ValidaReplica("", Codigo, "Financeiro.Ofi_Contas", "con_codigo", "con_descricao")
            If objDal.validaexclusao(Me.codigo) Then
                If objDal.validaexclusao2(Me.codigo) Then
                    If (tab.Rows.Count = 0) Then
                        ret = objDal.Excluir(Codigo)
                    End If
                Else
                    MsgBox("Esta conta não pode ser excluída. Está sendo utilizada no Contas a Receber! ")
                End If
            Else
                MsgBox("Esta conta não pode ser excluída. Está sendo utilizada no Contas a Pagar! ")
            End If
        Catch ex As Exception
            Throw New Exception("Exclusão não realizada!")
        Finally
            tab = Nothing
            objDal = Nothing
        End Try
        Return ret
    End Function
#End Region
#Region "Valida Campos obrigatórios"
    Public Function valida() As Boolean
        If Me.descricao.Trim = Nothing Or Me.descricao.Trim = "" Then Throw New Exception("Preencha a descrição.")
        If Me.codigo = Nothing Or Me.status <= 0 Then Throw New Exception("Preencha o campo status.")
        If (Me.tipoConta = "B" And Me.agencia = Nothing) Then
            Throw New Exception("Preencha o campo Agência!")
        End If
        Return True
    End Function
#End Region
#Region "Excluir"
    Function Excluir(ByVal Codigo As Integer, ByVal Nome As String) As Boolean 'EXcluir
        Dim ret As Boolean
        Dim tab As New DataTable
        Try
            objDal = New ContasDAL
            tab = objfuncoes.ValidaReplica(descricao, 0, "Financeiro.Ofi_Contas", "con_codigo", "con_descricao")

            If (tab.Rows.Count > 0) Then
                ret = objDal.Excluir(Codigo)
            Else
                ret = False
            End If
        Catch ex As Exception
            Throw New Exception("Exclusão não realizada!")
        Finally
            tab = Nothing
            objDal = Nothing
        End Try
        Return ret
    End Function
#End Region
#Region "Carrega"
    Private Sub carrega(codigo As Integer)
        Dim tab As DataTable
        Try
            objDal = New ContasDAL
            tab = objDal.localizar(codigo)
            If (tab.Rows.Count > 0) Then
                Me.codigo = Integer.Parse(tab.Rows(0)("con_codigo").ToString)
                Me.descricao = tab.Rows(0)("con_descricao").ToString
                Me.banco = Integer.Parse(tab.Rows(0)("ban_codigo").ToString)
                Me.dtabertura = tab.Rows(0)("con_dtabertura").ToString
                If (tab.Rows(0)("con_dtfechamento") Is DBNull.Value) Then
                    Me.dtfechamento = Nothing
                Else
                    Me.dtfechamento = tab.Rows(0)("con_dtfechamento").ToString
                End If

                Me.agencia = tab.Rows(0)("con_agencia").ToString
                Me.contacorrente = Integer.Parse(tab.Rows(0)("con_ctcorrente").ToString)
                Me.gerente = tab.Rows(0)("con_gerente").ToString
                Me.email = tab.Rows(0)("con_email").ToString
                Me.saldoinicial = Decimal.Parse(tab.Rows(0)("con_saldoinicial").ToString)
                Me.status = tab.Rows(0)("sta_codigo").ToString
                Me.tipoConta = tab.Rows(0)("con_tipo").ToString
            End If
        Catch ex As Exception
            Throw New Exception("Erro no Construtor")
        Finally
            objDal = Nothing
        End Try
    End Sub
#End Region
#Region "localizar"
    Function localizar() As DataTable 'Geral
        Dim tab As DataTable
        Try
            objDal = New ContasDAL
            tab = objDal.localizar()
        Catch ex As Exception
            Throw New Exception("Dados não encontrados!")
        Finally
            objDal = Nothing
        End Try
        Return tab
    End Function
#End Region
#Region "Buscar Filtro"
    Function buscar(ByVal descricao As String, tipo As Integer) As DataTable
        Dim ret As DataTable
        Try
            objDal = New ContasDAL
            ret = objDal.buscar(descricao, tipo)
        Catch ex As Exception
            Throw ex
        Finally
            objDal = Nothing
        End Try
        Return ret
    End Function
#End Region
#Region "Localiza Conta Período"
    Function localizaContaPeriodo(ByVal conta As Integer, ByVal dataIni As DateTime, ByRef datafim As DateTime) As DataTable 'buscar datas cbfiltro
        Dim ret As DataTable
        Try
            objDal = New ContasDAL
            If dataIni <= datafim Then
                ret = objDal.localizaContaPeriodo(conta, dataIni, datafim)
            Else : Throw New Exception("Data inical maior que data final")
            End If
        Catch ex As Exception
            Throw ex
        Finally
            objDal = Nothing
        End Try
        Return ret
    End Function
#End Region
#Region "Fluxo de Caixa"
    Function fluxodecaixa(ByVal dtini As Date, dtfim As Date) As DataTable
        Dim ret As DataTable
        Try
            objDal = New ContasDAL
            ret = objDal.fluxodecaixa(dtini, dtfim)
        Catch ex As Exception
            Throw ex
        Finally
            objDal = Nothing
        End Try
        Return ret
    End Function
#End Region
End Class
